//
//  Copyable.swift
//  iUtil
//
//  Created by wendachuan on 2019/7/25.
//  Copyright © 2019 wendachuan. All rights reserved.
//

import UIKit
import Runtime

/// 可复制协议
public protocol Copyable {
    
    /// 拷贝对象
    ///
    /// - Parameter object: 源对象
    /// - Throws:
    func copy(from object: Self) throws
}

public extension Copyable {

    /// 拷贝对象
    ///
    /// - Parameter object: 源对象
    /// - Throws:
    func copy(from object: Self) throws {
        let info = try typeInfo(of: type(of: object))
        
        var mirror: Mirror? = Mirror(reflecting: object)
        while mirror != nil {
            let _ = try mirror?.children.compactMap { (propertyName, propertyValue) in
                guard let propertyName = propertyName else {
                    throw NSError.init(errorCode: -1, errorDescription: "nil property name!")
                }
                
                var strongSelf = self
                let property = try info.property(named: propertyName)
                
                if case Optional<Any>.none = propertyValue {
                    
                } else {
                    try property.set(value: propertyValue, on: &strongSelf)
                }
            }
            mirror = mirror?.superclassMirror
        }
    }
}
